<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hrd extends MY_Controller
{
	var $current_user;
	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page('hrd');
		$this->config->load('acl_config');
		
		$this->load->model(array('M_employees', 'M_users', 'M_profile', 'M_enrollees', 'M_school_years'));
		$this->load->library(array('form_validation','grocery_CRUD','email'));
		$this->load->helper(array('url','form','student_photo','file'));
		$this->current_user = $this->session->userdata('username').' - '.$this->session->userdata('userType');
		$this->view_data['system_message'] = $this->_msg();
	}
	
	public function new_employee()
	{
		if($this->input->post('add_new_employee'))
		{
			$data = $this->input->post();
			unset($data['add_new_employee']);
			$this->M_employees->new_employee($data);
		}
	}
	
	public function edit_employee($hash= '')
	{
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$id = $x[0];
			if($this->M_employees->check_employee_id($id))
			{
				$this->view_data['employee_found'] = TRUE;
				
				$this->view_data['emp'] = $this->M_employees->_get_employee_data($id);
				$this->view_data['hash'] = $hash;
			
			
				if($this->input->post('edit_employee'))
				{
					$data = $this->input->post();
					$res = $this->M_employees->update_employee_profile($data,$id);
					
					if($res == TRUE)
					{
						$this->_msg('s','Successfully updated employee profile.','hrd/edit_employee/'.$hash);
					}else{
						$this->_msg('e','Unable to update employee profile.','hrd/edit_employee/'.$hash);
					}
				}
				
				if($this->input->post('upload_employee_photo'))
				{
					$config['upload_path'] = './assets/uploads/employees';
					$config['allowed_types'] = 'jpg';
					$config['max_size']	= '1000';
					$config['file_name'] = $hash;
					$config['overwrite'] = TRUE;
					
					$this->load->library('upload', $config);
					
					if ( ! $this->upload->do_upload())
					{
						$error = array('error' => $this->upload->display_errors());
						$this->view_data['system_message'] = $this->_msg('n',' '.$error['error']);
					}
					else
					{
						
						
						$data = array('upload_data' => $this->upload->data());
						//resize start
						$source_path = $data['upload_data']['full_path'];
						$target_path = './assets/uploads/thumbs';
						
						//create thumbs
						$thumb['image_library'] = 'gd2';
						$thumb['source_image']	= $source_path;
						$thumb['new_image']	= $target_path;
						$thumb['create_thumb'] = TRUE;
						$thumb['maintain_ratio'] = FALSE;
						$thumb['width']	 = 100;
						$thumb['height'] = 100;
						$thumb['overwrite'] = TRUE;
						$this->load->library('image_lib', $thumb); 
						$this->image_lib->resize();
						$this->image_lib->clear();
						sleep(3);
						
						//resize image
						$thumb2['image_library'] = 'gd2';
						$thumb2['source_image']	= $source_path;
						$thumb2['new_image']	= $data['upload_data']['file_path'];
						$thumb2['create_thumb'] = FALSE;
						$thumb2['maintain_ratio'] = TRUE;
						$thumb2['width'] = 180;
						$thumb2['height'] = 196;
						$thumb2['overwrite'] = TRUE;
						
						$this->image_lib->initialize($thumb2);
						$this->image_lib->resize();
						sleep(3);
						//resize end
		
						if($data)
						{
							$this->_msg('s','Image successfully uploaded. Changes will be applied in few minutes.','hrd/edit_employee/'.$hash);
						}else{
							$this->_msg('e','An error occured while trying to upload image.','hrd/edit_employee/'.$hash);
						}
					}			
				}
			
			}else{
				$this->view_data['employee_found'] = FALSE;
			}
			
		}else{
			show_404();
		}
		
		if($this->input->post('search'))
		{
			$employee = $this->input->post('student_search_data',TRUE);
			$current = $this->input->post('current',TRUE);
			$f_employee = strpos($employee,'-') > 0 ? explode('-',$employee) : FALSE;
			if($f_employee){
				$this->_msg('n','Employee Found','hrd/edit_employee/'.__link(intval($f_employee[0])));
			}else{
				$this->_msg('n','No Employee Found','hrd/edit_employee/'.$current);
			}
		}
	}
	
    function index()
    {
		$this->view_data['system_message'] = $this->_msg();
    }
	
	/*
		Function for employee management
	*/
	function employees()
	{
		$this->_init_pagnate_config();
		// $this->view_data['employee_data'] = $this->M_employees->get_employee_all();
		
		if($this->input->post('search'))
		{
			$employee = $this->input->post('student_search_data',TRUE);
			$f_employee = strpos($employee,'-') > 0 ? explode('-',$employee) : FALSE;
			if($f_employee){
				$this->_msg('n','Employee Found','hrd/edit_employee/'.__link(intval($f_employee[0])));
			}else{
				redirect('hrd/employees');
			}
		}else{
			$this->load->library('pagination');
			$this->pagnate_config['base_url'] = base_url().'hrd/employees';
			$this->pagnate_config['per_page'] = 15;
			$this->pagnate_config["uri_segment"] = 3;
			$this->pagnate_config['total_rows'] = $this->M_employees->count_employees();
			$this->pagination->initialize($this->pagnate_config);
			$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
			$this->view_data['employee_data'] = $this->M_employees->get_employee_all($this->pagnate_config['per_page'],$page);
			$this->view_data['links'] = $this->pagination->create_links();
		}
	}
	
	function employee_bin()
	{
		redirect('employee_settings/employee_bin', 'location');
	}
	
	function profile()
	{
		$user_string = explode("-", $this->current_user);
		redirect('employee_settings/change_profile/' . trim($user_string[0], " "), 'location');
	}
	
	function settings()
	{
		$user_string = explode("-", $this->current_user);
		redirect('employee_settings/change_password/' . trim($user_string[0], " "), 'location');
	}
	
	/*=== AUXILIARY FUNCTIONS ===*/
	function update_username($password, $id, $un, $ut)
	{
		$this->form_validation->set_rules('username','Username','trim|required');
		$this->form_validation->set_rules('password','Password','required');
		
		if($this->form_validation->run() == FALSE) // If form does not have empty values.
		{
			$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
		}else
		{
			$i_username = $this->input->post('username');
			$i_password = $this->input->post('password');
			
			if($this->M_users->verify_password($i_password, $id))
			{
				$data = array('username' => $i_username,
							'updated_at'=>NOW);
				if($this->M_users->check_duplicates($i_username, $id))
				{
					if($this->M_users->update_user($id, $data))
					{
						$this->current_user = $this->session->userdata($data['username'] .' - '. $ut);
						
						$user_data = $this->M_profile->get_user_profile($data['username']);
						if($user_data != FALSE)
						{
							foreach($user_data as $u_data)
							{
								$emp_id = $u_data->emp_id; // primary key for employees table
								$id = $u_data->id; // primary key for users table
								$password = $u_data->hashed_password;
							}
						}else
						{
							$user_data = $this->M_profile->get_user_details($un);
			
							$id = $user_data->id; // primary key for users table
							$password = $user_data->hashed_password;
						}
						
						$this->view_data['user_data'] = $user_data;
						$this->view_data['system_message']="<div class='success'>Update Success. <a href='auth/login/hrd'>Click here to logout</a></div>";
						$this->session->sess_destroy();
					}else
					{
						$user_data = $this->M_profile->get_user_profile($this->session->userdata('username'));
						if($user_data != FALSE)
						{
							foreach($user_data as $u_data)
							{
								$emp_id = $u_data->emp_id; // primary key for employees table
								$id = $u_data->id; // primary key for users table
								$password = $u_data->hashed_password;
							}
						}else
						{
							$user_data = $this->M_profile->get_user_details($un);
			
							$id = $user_data->id; // primary key for users table
							$password = $user_data->hashed_password;
						}
						$this->view_data['user_data'] = $user_data;
						$this->view_data['system_message']='<div class="notice">No changes done.</div>';
					}
				}else
				{
					$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
					$this->view_data['system_message']='<div class="notice">Username is not available.</div>';
				}
			}else
			{
				$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
				$this->view_data['system_message']='<div class="error">Invalid username and password combination.</div>';
			}
		}
	}
	
	function change_password($password, $id)
	{
		$this->form_validation->set_rules('password','Password','required');
		$this->form_validation->set_rules('new_password','New Password','required|matches[confirm_password]');
		$this->form_validation->set_rules('confirm_password','Confirm Password','required');
		
		if($this->form_validation->run() == FALSE) // If form does not have empty values.
		{
			$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
		}else
		{
			$i_password = $this->input->post('password');
			if($this->M_users->verify_password($i_password, $id))
			{
				if($this->M_users->change_pass($this->input->post('new_password'), $id))
				{
					$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
					$this->view_data['system_message']='<div class="success">Update Success. Password Changed.</div>';
				}else
				{
					$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
					$this->view_data['system_message']='<div class="error">Update Error. Please try again later.</div>';
				}
			}else
			{
				$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
				$this->view_data['system_message']='<div class="error">User Error. Password is not recognized.</div>';
			}
		}
	}
	
	function change_username_password($password, $id, $un, $ut)
	{
		$this->form_validation->set_rules('username','Username','trim|required');
		$this->form_validation->set_rules('password','Password','required');
		$this->form_validation->set_rules('password','Password','required');
		$this->form_validation->set_rules('new_password','New Password','required|matches[confirm_password]');
		$this->form_validation->set_rules('confirm_password','Confirm Password','required');
		
		if($this->form_validation->run() == FALSE) // If form does not have empty values.
		{
			$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
		}else
		{
			$i_username = $this->input->post('username');
			$i_password = $this->input->post('password');
			
			if($this->M_users->verify_password($i_password, $id))
			{
				$data = array('username' => $i_username,
							'updated_at'=>NOW);
				
				if($this->M_users->check_duplicates($i_username, $id))
				{
					if($this->M_users->update_user($id, $data))
					{
						if($this->M_users->change_pass($this->input->post('new_password'), $id))
						{
							$this->current_user = $this->session->userdata($data['username'] .' - '. $ut);
						
							$user_data = $this->M_profile->get_user_profile($data['username']);
							foreach($user_data as $u_data)
							{
								$emp_id = $u_data->emp_id; // primary key for employees table
								$id = $u_data->id; // primary key for users table
								$password = $u_data->hashed_password;
							}
							$this->view_data['user_data'] = $user_data;
							$this->view_data['system_message']="<div class='success'>Update Success. <a href='auth/login/hrd'>Click here to logout</a></div>";
							$this->session->sess_destroy();
						}else
						{
							$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
							$this->view_data['system_message']='<div class="error">Update Error. Password has not been changed. Please log-out and login again.</div>';
							$this->session->sess_destroy();
						}
					}else
					{
						$this->change_password($password, $id);
					}					
				}else
				{
					$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
					$this->view_data['system_message']='<div class="notice">Username is not available.</div>';
				}
			}else
			{
				$this->view_data['user_data'] = $this->M_profile->get_user_profile($this->session->userdata('username'));
				$this->view_data['system_message']='<div class="error">Invalid username and password combination.</div>';
			}
		}
	}
}

?>